package com.qupai.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.qupai.constant.MessageConstant;
import com.qupai.constant.StatusConstant;
import com.qupai.dto.EmployeeDTO;
import com.qupai.dto.EmployeeLoginDTO;
import com.qupai.dto.EmployeePageQueryDTO;
import com.qupai.entity.Employee;
import com.qupai.exception.AccountLockedException;
import com.qupai.exception.AccountNotFoundException;
import com.qupai.exception.PasswordErrorException;
import com.qupai.mapper.EmployeeMapper;
import com.qupai.result.PageResult;
import com.qupai.service.EmployeeService;
import jakarta.annotation.Resource;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import java.util.List;

@Service
public class EmployeeServiceImpl extends ServiceImpl<EmployeeMapper,Employee> implements EmployeeService {

    @Resource
    private EmployeeMapper employeeMapper;

    /**
     * 员工登录
     * @param employeeLoginDTO 员工登录信息
     * @return 登录成功的员工信息
     */
    @Override
    public Employee login(EmployeeLoginDTO employeeLoginDTO) {
        String username= employeeLoginDTO.getUsername();
        String password= employeeLoginDTO.getPassword();
        //获取登录用户的角色
        Integer classification = employeeLoginDTO.getClassification();

        // 根据用户名查询数据库
        QueryWrapper<Employee>wrapper=new QueryWrapper<>();
        wrapper.lambda()
                .eq(Employee::getClassification,classification)
                .eq(Employee::getUsername,username);
        Employee employee = employeeMapper.selectOne(wrapper);

        // 判断查询结果是否为null,根据名字查询如果账户里面没有那个人则退出查询
        // 如果为null，则抛出AccountNotFoundException异常，并返回错误信息
        if (employee == null) {
            throw new AccountNotFoundException(MessageConstant.ACCOUNT_NOT_FOUND);
        }

        // 判断密码是否正确，如果密码不正确，则抛出异常，并返回错误信息
        //密码比对
        boolean flag= password.equals(employee.getPassword()) ||
                DigestUtils.md5DigestAsHex(password.getBytes()).equals(employee.getPassword());
        if (!flag) {
            throw new PasswordErrorException(MessageConstant.PASSWORD_ERROR);
        }

        if (employee.getStatus().equals(StatusConstant.DISABLE)){
            //账号被锁定
            throw new AccountLockedException(MessageConstant.ACCOUNT_LOCKED);
        }

        // 返回查询到的员工信息
        return employee;

    }

    @Override
    public void save(EmployeeDTO employeeDTO) {

        Employee employee=new Employee();

        //将employeeDTO中的数据复制到employee中
        BeanUtils.copyProperties(employeeDTO,employee);

        //其余的自己添加
        //设置账号状态,默认为启用
        if (employee.getStatus()==null){
            employee.setStatus(StatusConstant.ENABLE);
        }


        //设置默认密码，123456,并md5转换
        employee.setPassword(DigestUtils.md5DigestAsHex("123456".getBytes()));
        //通过注入实现设置创建时间和修改时间和修改人等等

        //调用mapper中的方法进行添加
        employeeMapper.insert(employee);
    }

//    @Override
//    public PageResult pageQuery(EmployeePageQueryDTO employeePageQueryDTO) {
//        //开始分页查询
//        //在mybatisX里面默认添加limit
//        //在mybatisX里面默认添加了分页插件
//        PageHelper.startPage(employeePageQueryDTO.getPage(),employeePageQueryDTO.getPageSize());
//
//        //遵循PageHelper返回Page<Employee> page对象
//        //调用mapper
//        Page<Employee> page=employeeMapper.pageQueuery(employeePageQueryDTO);
//
//        //总数和每页记录数
//        long total = page.getTotal();
//        int pages = page.getPages();
//        //获取记录
//        List<Employee> records = page.getResult();
//
//        return new PageResult(total,pages,records);
//
//    }

    @Override
    public PageResult pageQuery(EmployeePageQueryDTO employeePageQueryDTO) {
        //使用mybatisPlus自带的分页插件
        //mybatisX里面默认添加的分页插件和该插件只能存在一个，如果想转换必须导包
        //mybatisX里面的属性为int
        //mybatisPlus里面的属性为long

        // 1.构建分页条件
        Page<Employee> page = employeePageQueryDTO.toMpPageDefaultSortByCreateTimeDesc();

        // 2.分页查询
        Page<Employee> p=lambdaQuery()
                .like(employeePageQueryDTO.getName() != null,Employee::getName, employeePageQueryDTO.getName())
                .page(page);

        // 3.调用插件获得数据
        //获得总的记录数
        long total = p.getTotal();
        //获得总的页数
        long pages = p.getPages();
        //获得当前页数据集合
        List<Employee> records = p.getRecords();

        // 4.返回封装好的分页结果
        return new PageResult(total,pages,records);
    }

    /**
     * 启用或禁用员工账号
     */
    @Override
    public void startOrStop(Integer status, Long id) {

        //用builder来实现
        Employee employee=Employee.builder()
                .status(status)
                .id(id)
                .build();

//        employeeMapper.update(employee);
        employeeMapper.updateById(employee);
    }

    /**
     * 根据id查询员工
     */
    @Override
    public Employee getById(Long id) {
//        Employee employee=employeeMapper.getById(id);
        Employee employee=employeeMapper.selectById(id);
        //隐藏密码，返回给前端回显
        employee.setPassword("****");
        return employee;
    }

    @Override
    public void update(EmployeeDTO employeeDTO) {
        Employee employee = new Employee();
        BeanUtils.copyProperties(employeeDTO, employee);

//        employeeMapper.update(employee);
        employeeMapper.updateById(employee);
    }

}
